package com.cherrish.demo.myspring.framework.webmvc.servlet;

import com.cherrish.demo.myspring.framework.annotation.*;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author cherrish
 * @name CDispatcherServlet
 * @date 2019/5/8 22:25
 * @desc TODO
 */
public class CDispatcherServlet extends HttpServlet{
    private Properties contextConfig = new Properties();
    private List<String> classNames = new ArrayList<>();
    private Map<String, Object> ioc = new HashMap<>();
    //private Map<String, Method> handlerMapping = new HashMap<>();
    private List<Handler> handlerMapping = new ArrayList<>();


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            doDispatch(req, resp);
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    private void doDispatch(HttpServletRequest req, HttpServletResponse resp) throws IOException, InvocationTargetException, IllegalAccessException {
        Handler handler = getHandler(req);
        if(null == handler){
            resp.getWriter().write("404 Not Found");
            return;
        }

        // 获取方法参数列表
        Class<?>[] paramsTypes = handler.method.getParameterTypes();
        // 保存所有需要自动赋值的参数值
        Object[] paramsValues = new Object[paramsTypes.length];

        Map<String, String[]> params = req.getParameterMap();

        for(Map.Entry<String, String[]> param : params.entrySet()){
            String value = Arrays.toString(param.getValue()).replaceAll("\\[\\]", "").replaceAll("", "");

            if(handler.paramIndexMapping.containsKey(param.getKey())){
                int index = handler.paramIndexMapping.get(param.getKey());
                paramsValues[index] = convert(paramsTypes[index], value);
            }
        }

        int reqIndex = handler.paramIndexMapping.get(HttpServletRequest.class.getName());
        paramsValues[reqIndex] = req;
        int respIndex = handler.paramIndexMapping.get(HttpServletResponse.class.getName());
        paramsValues[respIndex] = resp;

        handler.method.invoke(handler.controller, paramsValues);
    }

    private Object convert(Class<?> paramsType, String value) {
        return null;
    }

    @Override
    public void init(ServletConfig config) throws ServletException {
        //从这里开始启动
        //1. 加载配置文件
        doLoadConfig(config.getInitParameter("contextConfigLocation"));
        //2. 扫描所有相关类
        doScan(contextConfig.getProperty("scan.package"));
        //3. 初始化所有相关类
        doInitInstance();
        //4. 自动注入
        doAutowired();
        //5. 初始化HandlerMapping
        doInitHandlerMapping();
    }

    private void doInitHandlerMapping() {
        if(ioc.isEmpty()){
            return;
        }
        for(Map.Entry<String, Object> entry : ioc.entrySet()){
            Class<?> clazz = entry.getValue().getClass();
            if(!clazz.isAnnotationPresent(CController.class)){
                continue;
            }
            String baseUrl = "";
            if(clazz.isAnnotationPresent(CRequestMapping.class)){
                CRequestMapping requestMapping = clazz.getAnnotation(CRequestMapping.class);
                baseUrl = requestMapping.value();
            }
            for(Method method : clazz.getMethods()){
                if(!method.isAnnotationPresent(CRequestMapping.class)){
                    return;
                }
                CRequestMapping requestMapping = method.getAnnotation(CRequestMapping.class);
                String methodUrl = ("/" + baseUrl + requestMapping.value()).replaceAll("/+", "/");
                //handlerMapping.put(methodUrl, method);
                Pattern pattern = Pattern.compile(methodUrl);
                handlerMapping.add(new Handler(pattern, entry.getValue(), method));
                System.out.println("Mapping: " + methodUrl + "" + method);
            }
        }
    }

    private void doAutowired() {
        if(ioc.isEmpty()){
            return;
        }
        //循环IOC容器中的所有类, 然后对需要自动赋值的属性进行赋值
        for(Map.Entry<String, Object> entry : ioc.entrySet()){
            Field[] fields = entry.getValue().getClass().getDeclaredFields();
            for(Field field : fields){
                if(!field.isAnnotationPresent(CAutowired.class)){
                    continue;
                }
                CAutowired autowired = field.getAnnotation(CAutowired.class);
                String beanName = autowired.value().trim();
                if("".equals(beanName)){
                    beanName = field.getType().getName();
                }
                field.setAccessible(true);
                try {
                    field.set(entry.getValue(), ioc.get(beanName));
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                    continue;
                }
            }
        }
    }

    private void doInitInstance() {
        if (classNames.isEmpty()){
            return;
        }
        for(String className : classNames){
            try {
                Class<?> clazz = Class.forName(className);
                if(clazz.isAnnotationPresent(CController.class)){
                    //key默认是类名首字母小写
                    String beanName = toLowerCaseInitial(clazz.getName());
                    ioc.put(beanName, clazz.newInstance());
                }else if(clazz.isAnnotationPresent(CService.class)){

                    //2. 如果自定义了名字优先使用自定义的
                    CService service = clazz.getAnnotation(CService.class);
                    String beanName = service.value();

                    //1. 默认采用默认首字母小写
                    if("".equals(beanName.trim())){
                        beanName = toLowerCaseInitial(clazz.getName());
                    }
                    Object instance = clazz.newInstance();
                    ioc.put(beanName, instance);
                    //3. 根据接口类型赋值
                    for(Class<?> i : clazz.getInterfaces()){
                        ioc.put(i.getName(), instance);
                    }
                }else {
                    continue;
                }
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InstantiationException e) {
                e.printStackTrace();
            }
        }
    }

    private void doScan(String scanPackage) {
        URL url = this.getClass().getClassLoader().getResource("/" + scanPackage.replaceAll("\\.", "/"));
        File classDir = new File(url.getFile());
        for(File file : classDir.listFiles()){
            if(file.isDirectory()){
                doScan(scanPackage + "." + file.getName());
            }else {
                String className = scanPackage + "." + file.getName().replace(".class", "");
                classNames.add(className);
            }
        }
    }

    private void doLoadConfig(String contextConfigLocation) {
        InputStream is = this.getClass().getClassLoader().getResourceAsStream(contextConfigLocation);
        try {
            contextConfig.load(is);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(null != is){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private String toLowerCaseInitial(String str){
        char[] chs = str.toCharArray();
        chs[0] += 32;
        return String.valueOf(chs);
    }

    private class Handler{
        //保存方法对应的实例
        protected Object controller;
        //保存映射的方法
        protected Method method;
        private Pattern pattern;
        //参数顺序
        protected Map<String, Integer> paramIndexMapping;

        protected Handler(Pattern pattern, Object controller, Method method){
            this.controller = controller;
            this.method = method;
            this.pattern = pattern;

            paramIndexMapping = new HashMap<>();
        }
        private void putParamIndexMapping(Method method){
            // 提取方法中加了注解的参数
            Annotation[][] params = method.getParameterAnnotations();
            for(int i = 0; i < params.length; i++){
                for(Annotation annotation : params[i]){
                    if(annotation instanceof CRequestParam){
                        String paramName = ((CRequestParam) annotation).value();
                        if(!"".equals(paramName.trim())){
                            paramIndexMapping.put(paramName, i);
                        }
                    }
                }
            }
            // 提取方法中的request 和 response参数
            Class<?>[] paramsTypes = method.getExceptionTypes();
            for(int i = 0; i < paramsTypes.length; i++){
                Class<?> type = paramsTypes[i];
                if(type == HttpServletRequest.class || type == HttpServletResponse.class){
                    paramIndexMapping.put(type.getName(), i);
                }
            }
        }
    }

    private Handler getHandler(HttpServletRequest req){
        if(handlerMapping.isEmpty()){
            return null;
        }
        String uri = req.getRequestURI();
        String contextPath = req.getContextPath();
        uri = uri.replace(contextPath, "").replaceAll("/+", "/");
        for(Handler handler : handlerMapping){
            Matcher matcher = handler.pattern.matcher(uri);
            if(matcher.matches()){
                return handler;
            }
        }
        return null;
    }
}
